package router.base.router;

import java.util.concurrent.ConcurrentLinkedQueue;

import router.base.linker.RSLinker;
import router.message.Message;

import logger.Loggable;
import logger.Logger;



/**Describes a ZerdNet router object.
 * This is not strictly speaking a router, but a sort of hub dispatching message to every attached client.
 * Filtering is up to the clients.
 * @author Zerdligham
 */

public class Router implements Loggable {
	protected ConcurrentLinkedQueue<RSLinker> connexionList = new ConcurrentLinkedQueue<>();
	protected Logger logger = new Logger();
	
	public void connect(RSLinker linker) {
		logger.info("New connexion : " + linker.getName());
		connexionList.add(linker);
	}
	
	public void disconnect(RSLinker linker) {
		connexionList.remove(linker);
	}
	
	public synchronized void send(Message msg) {
		boolean ack = false;
		for(RSLinker linker : connexionList) {
			if(linker.offer(msg)) {
				ack = true;
			}
		}
		
		if(ack) {
			logger.out("Message transmit : " + msg);
		} else {
			logger.err("Pas de destinataire pour le message suivant : " + msg);
		}
		
	}
	
	@Override
	public Logger getLogger() {
		return logger;
	}
	
	public void close() {
		logger.info("Fermeture de toutes les connexions");
		for(RSLinker l : connexionList) {
			l.kick();
		}
	}

}
